import {
  createStore,
  Plugin,
  PluginFunctions,
  RenderViewer,
  Slot,
} from "../../core";

import EnterFullScreen, { EnterFullScreenProps } from "./EnterFullScreen";
import EnterFullScreenButton from "./EnterFullScreenButton";
import EnterFullScreenMenuItem, {
  EnterFullScreenMenuItemProps,
} from "./EnterFullScreenMenuItem";
import ExitFullScreenButton from "./ExitFullScreenButton";
import type { Zoom } from "./types";

import StoreProps from "./StoreProps";
import { ReactElement, useMemo } from "react";

interface FullScreenPlugin extends Plugin {
  EnterFullScreen: (props: EnterFullScreenProps) => ReactElement;
  EnterFullScreenButton: () => ReactElement;
  EnterFullScreenMenuItem: (
    props: EnterFullScreenMenuItemProps
  ) => ReactElement;
}

export interface FullScreenPluginProps {
  onEnterFullScreen?(zoom: Zoom): void;
  onExitFullScreen?(zoom: Zoom): void;
}

const fullScreenPlugin = (props?: FullScreenPluginProps): FullScreenPlugin => {
  const store = useMemo(() => createStore<StoreProps>({}), []);

  /* eslint-disable @typescript-eslint/no-empty-function */
  const onEnterFullScreen =
    props && props.onEnterFullScreen ? props.onEnterFullScreen : () => {};
  const onExitFullScreen =
    props && props.onExitFullScreen ? props.onExitFullScreen : () => {};
  /* eslint-enable @typescript-eslint/no-empty-function */

  const EnterFullScreenDecorator = (props: EnterFullScreenProps) => (
    <EnterFullScreen
      {...props}
      store={store}
      onEnterFullScreen={onEnterFullScreen}
      onExitFullScreen={onExitFullScreen}
    />
  );

  const EnterFullScreenButtonDecorator = () => (
    <EnterFullScreenDecorator>
      {(renderProps) => <EnterFullScreenButton {...renderProps} />}
    </EnterFullScreenDecorator>
  );

  const EnterFullScreenMenuItemDecorator = (
    props: EnterFullScreenMenuItemProps
  ) => (
    <EnterFullScreenDecorator>
      {(p) => (
        <EnterFullScreenMenuItem
          onClick={() => {
            p.onClick();
            props.onClick();
          }}
        />
      )}
    </EnterFullScreenDecorator>
  );

  const ExitFullScreenDecorator = () => <ExitFullScreenButton store={store} />;

  const renderViewer = (props: RenderViewer): Slot => {
    const currentSlot = props.slot;
    if (currentSlot.subSlot) {
      currentSlot.subSlot.children = (
        <>
          <ExitFullScreenDecorator />
          {currentSlot.subSlot.children}
        </>
      );
    }

    return currentSlot;
  };

  return {
    install: (pluginFunctions: PluginFunctions) => {
      store.update("getPagesContainer", pluginFunctions.getPagesContainer);
      store.update("zoom", pluginFunctions.zoom);
    },
    renderViewer,
    EnterFullScreen: EnterFullScreenDecorator,
    EnterFullScreenButton: EnterFullScreenButtonDecorator,
    EnterFullScreenMenuItem: EnterFullScreenMenuItemDecorator,
  };
};

export default fullScreenPlugin;
